import java.util.Arrays;

/**
 * @Author: Lenovo
 * @Date: 2024/7/23 9:50
 * @description:
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;
    public TestHeap(){
        this.elem = new int[10];
    }

    public void initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            this.usedSize++;
        }
    }
    public void createHeap(){
        for (int parent = (this.usedSize-1-1)/2;parent>=0;parent--){
            shiftDown(parent,usedSize);
        }
    }

    private void shiftDown(int parent, int usedSize) {
        int child = 2 * parent + 1;
        while (child < usedSize){
            //左右孩子都存在，并且左节点的值 小于 父亲结点的值
            if (child + 1 <usedSize && elem[child] < elem[child + 1]){
                child ++;
            }
            if (elem[parent] < elem[child]){
                swap(elem,parent,child);
                parent = child;
                child = 2 * parent + 1;
            }else {
                break;
            }
        }
    }

    private void swap(int[] elem, int parent, int child) {
        int tmp = elem[parent];
        elem[parent] = elem[child];
        elem[child] = tmp;
    }
    public void offer(int val){
        if (isFull()){
            this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int parent = (child - 1)/2;
        while (parent>=0){
            if (elem[parent] < elem[child]){
                swap(elem,parent,child);
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }

    public boolean isFull(){
        return this.usedSize == this.elem.length;
    }
    public boolean isEmpty(){
        return this.usedSize == 0;
    }
    public int peek(){
        if (isEmpty()){
            return -1;
        }
        return elem[0];
    }
    public int poll(){
        if (isEmpty()){
            return -1;
        }
        int val = elem[0];
        swap(elem,0,usedSize-1);
        shiftDown(0,usedSize-1);
        usedSize--;
        return val;
    }


}
